package cn.hengzhu.main_manager.web.openAPi.openApiToInner;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.hengzhu.main_manager.repository.dao.AccessRecordMapper;
import cn.hengzhu.main_manager.repository.dao.ManageCaseBoxMapper;
import cn.hengzhu.main_manager.repository.dao.ManageCaseMapper;
import cn.hengzhu.main_manager.repository.dao.SysConstMapper;
import cn.hengzhu.main_manager.repository.domain.AccessRecord;
import cn.hengzhu.main_manager.repository.domain.ManageCase;
import cn.hengzhu.main_manager.repository.domain.ManageCaseBox;
import cn.hengzhu.main_manager.repository.domain.ManageCaseBoxExample;
import cn.hengzhu.main_manager.repository.domain.ManageCaseExample;
import cn.hengzhu.main_manager.repository.domain.SysConst;
import cn.hengzhu.main_manager.repository.domain.SysConstExample;
import cn.hengzhu.main_manager.service.ManageCaseBoxService;
import cn.hengzhu.main_manager.utils.DateTimeHelper;
import cn.hengzhu.main_manager.utils.SecurityUtil;
import cn.hengzhu.main_manager.utils.config.AllConst;
import cn.hengzhu.main_manager.utils.config.AppConfig;

/**
 * @author liuCheng
 * @since 2019年1月3日 上午10:59:11 游泳馆的接口
 * 
 */

@Controller
@RequestMapping("/openApiToInner")
public class SwimController {
	@Autowired
	private ManageCaseBoxMapper manageCaseBoxMapper;
	@Autowired
	private ManageCaseMapper manageCaseMapper;
	@Autowired
	private ManageCaseBoxService manageCaseBoxService;
	@Autowired
	private AccessRecordMapper accessRecordMapper;
	@Autowired
	private SysConstMapper sysConstMapper;

	public static void main(String[] args) {
		Long currentTimeMillis = System.currentTimeMillis();
		System.out.println(currentTimeMillis);
		Date ad=new Date(currentTimeMillis);
		System.out.println(ad);
		System.out.println(new Date());
		String sha1 = SecurityUtil.sha1(currentTimeMillis.toString());
		System.out.println(sha1);
	}

	/**
	 * @author liuCheng
	 * @since 2019年1月3日 上午11:01:14
	 * @param
	 * @return 存物
	 */
	@ResponseBody
	@RequestMapping("/openBoxToSwim")
	public Map<String, Object> openBoxToSwim(String num, String mac, Long timestamp, String token) {
		Map<String, Object> map = new HashMap<>();
		Date date = new Date();
		String dateStr = DateTimeHelper.formatDateTimetoString(date, DateTimeHelper.FMT_yyyyMMdd);
		String sha1 = SecurityUtil.sha1(timestamp.toString());
		if (sha1.equals(token)) {
			
			long time = new Date().getTime();
			SysConstExample sysExample = new SysConstExample();
			sysExample.createCriteria().andNameEqualTo(AppConfig.REQEST_TIMEOUT);
			List<SysConst> selectByExample = sysConstMapper.selectByExample(sysExample);
			SysConst sysConst = selectByExample.get(0);
			String value = sysConst.getValue();
			Long valueOf = Long.valueOf(value);
			if (time - timestamp < valueOf) {

				// 查询此储物柜属于哪个公司
				ManageCaseExample manageCaseExample = new ManageCaseExample();
				manageCaseExample.createCriteria().andCaseNoEqualTo(mac);
				List<ManageCase> manageCaseList = manageCaseMapper.selectByExample(manageCaseExample);
				if (!manageCaseList.isEmpty()) {
					ManageCase manageCase = manageCaseList.get(0);
					Integer compId = manageCase.getCompId();
					// 查询此公司的储物柜
					ManageCaseExample allManageCaseExampl = new ManageCaseExample();
					allManageCaseExampl.createCriteria().andCompIdEqualTo(compId);
					List<ManageCase> allManageCaseByComp = manageCaseMapper.selectByExample(allManageCaseExampl);

					List<String> caseNoList = allManageCaseByComp.stream()
							.collect(Collectors.mapping(ManageCase::getCaseNo, Collectors.toList()));

					ManageCaseBoxExample manageCaseBoxExample = new ManageCaseBoxExample();
					manageCaseBoxExample.createCriteria().andUserIdEqualTo(num).andCaseNoIn(caseNoList)
							.andUseStatusEqualTo((byte) 1).andIsDelEqualTo((byte) 0);
					List<ManageCaseBox> manageCaseBoxList = manageCaseBoxMapper.selectByExample(manageCaseBoxExample);

					if (!manageCaseBoxList.isEmpty()) {// 已存
						ManageCaseBox manageCaseBox = manageCaseBoxList.get(0);
						
						//确定是同一组储物柜，否则不是同一组储物柜
						if(mac.equals(manageCaseBox.getCaseNo())){
							Integer doorNum = manageCaseBox.getDoorNum();
							// 插入取物记录
							AccessRecord accessRecord = new AccessRecord();
							accessRecord.setBoxId(manageCaseBox.getId());
							accessRecord.setCreateDay(dateStr);
							accessRecord.setCreateTime(date);
							accessRecord.setCreateTime(date);
							accessRecord.setCreateTime(date);
							accessRecord.setCreateTime(date);
							accessRecord.setSource(AllConst.ACCESS_RECORD_SOURCE.SWIMING_SOURCE);
							accessRecord.setType(AllConst.ACCESS_RECORD_TYPE.GET_TYPE);
							accessRecord.setUserId(num);
							accessRecord.setUseTime(date.getTime() - manageCaseBox.getSaveTime().getTime());
							accessRecordMapper.insertSelective(accessRecord);
							map.put("code", 200);
							map.put("doorNum", doorNum);
							map.put("message", "开启" + doorNum + "号门成功");
						}else{
							map.put("code", 430);
							map.put("message", "用户同时只能使用一个储物柜，请到存物柜进行操作");
						}
					} else {// 没有就随机分配
						ManageCaseBox manageCaseBox = manageCaseBoxMapper.getRandomDoorNum(mac);
						if (null != manageCaseBox) {
							Integer doorNum = manageCaseBox.getDoorNum();
							Integer boxId = manageCaseBox.getId();
							Integer version = manageCaseBox.getVersion();
							ManageCaseBox record = new ManageCaseBox();
							record.setId(boxId);
							record.setSaveTime(new Date());
							record.setUseStatus((byte) 1);
							record.setVersion(version + 1);
							record.setUserId(num);
							record.setSaveSource(AllConst.ACCESS_RECORD_SOURCE.SWIMING_SOURCE);
							ManageCaseBoxExample updateManageCaseBoxExample = new ManageCaseBoxExample();
							updateManageCaseBoxExample.createCriteria().andIdEqualTo(boxId).andVersionEqualTo(version);
							int updateByExampleSelective = manageCaseBoxMapper.updateByExampleSelective(record,
									updateManageCaseBoxExample);
							if (updateByExampleSelective == 0) {
								map.put("code", 400);
								map.put("message", "开启失败，请重试！");
							} else {// 插入存物记录
								AccessRecord accessRecord = new AccessRecord();
								accessRecord.setBoxId(boxId);
								accessRecord.setCreateDay(dateStr);
								accessRecord.setCreateTime(date);
								accessRecord.setSource(AllConst.ACCESS_RECORD_SOURCE.SWIMING_SOURCE);
								accessRecord.setType(AllConst.ACCESS_RECORD_TYPE.SAVE_TYEP);
								accessRecord.setUserId(num);
								accessRecordMapper.insertSelective(accessRecord);
								map.put("code", 200);
								map.put("doorNum", doorNum);
								map.put("message", "开启" + doorNum + "号门成功");

							}

						} else {
							map.put("code", 400);
							map.put("message", "此储物柜没有剩余的箱门，请选择其他箱门！");
						}
					}
				} else {
					map.put("code", 400);
					map.put("message", "此储物柜不存在");
				}
				
			}else{
				map.put("code", 555);
				map.put("message", "请求超时");
			}
			
			
		} else {
			map.put("code", 500);
			map.put("message", "不要瞎几把搞");
		}
		return map;
	}

	/**
	 * @author liuCheng
	 * @since 2019年1月21日 上午9:26:31
	 * @return 柜体清除
	 */
	@ResponseBody
	@RequestMapping("/clearBoxToSwimToCase")
	public Map<String, Object> clearBoxToSwimToCase(Integer doorNum, String mac, Long timestamp, String token) {
		Map<String, Object> map = new HashMap<>();
		Date date=new Date();
		String sha1 = SecurityUtil.sha1(timestamp.toString());
		if (sha1.equals(token)) {
			long time = new Date().getTime();
			SysConstExample sysExample = new SysConstExample();
			sysExample.createCriteria().andNameEqualTo(AppConfig.REQEST_TIMEOUT);
			List<SysConst> selectByExample = sysConstMapper.selectByExample(sysExample);
			SysConst sysConst = selectByExample.get(0);
			String value = sysConst.getValue();
			Long valueOf = Long.valueOf(value);
			if (time - timestamp < valueOf) {
				if (null != doorNum) {
					// 查询
					ManageCaseBoxExample manageCaseBoxExample = new ManageCaseBoxExample();
					manageCaseBoxExample.createCriteria().andCaseNoEqualTo(mac).andDoorNumEqualTo(doorNum)
							.andIsDelEqualTo((byte) 0);
					List<ManageCaseBox> manageCaseBoxList = manageCaseBoxMapper.selectByExample(manageCaseBoxExample);
					ManageCaseBox manageCaseBox = manageCaseBoxList.get(0);
					Integer boxId = manageCaseBox.getId();
					try {
						manageCaseBoxService.clearBoxToSwimToCase(boxId,date);
						map.put("code", 200);
						map.put("message", "清柜成功！");
					} catch (Exception e) {
						map.put("code", 400);
						map.put("message", "清柜失败！");
					}
				} else {
					try {
						manageCaseBoxService.clearBoxToSwimToCaseBatch(mac,date);
						map.put("code", 200);
						map.put("message", "清柜成功！");

					} catch (Exception e) {
						map.put("code", 400);
						map.put("message", "清柜失败！");
					}
				}
				
			}else{
				map.put("code", 555);
				map.put("message", "请求超时");
				
			}
			
			
		} else {
			map.put("code", 500);
			map.put("message", "不要瞎几把搞");
		}
		return map;
	}

	/**
	 * @author liuCheng
	 * @since 2019年1月23日 下午1:25:15
	 * @param doorNum
	 * @param mac
	 * @param timestamp
	 * @param token
	 * @return 柜体开门 doorNum==null 为一键开门
	 */
	@ResponseBody
	@RequestMapping("/openBoxToSwimToCase")
	public Map<String, Object> openBoxToSwimToCase(Integer doorNum, String mac, Long timestamp, String token,Long actionTime) {
		Map<String, Object> map = new HashMap<>();
		Date date=new Date(actionTime);
		String dateStr = DateTimeHelper.formatDateTimetoString(date, DateTimeHelper.FMT_yyyyMMdd);
		String sha1 = SecurityUtil.sha1(timestamp.toString());
		if (sha1.equals(token)) {
			long time = new Date().getTime();
			SysConstExample sysExample = new SysConstExample();
			sysExample.createCriteria().andNameEqualTo(AppConfig.REQEST_TIMEOUT);
			List<SysConst> selectByExample = sysConstMapper.selectByExample(sysExample);
			SysConst sysConst = selectByExample.get(0);
			String value = sysConst.getValue();
			Long valueOf = Long.valueOf(value);
			if (time - timestamp < valueOf) {
				if (null != doorNum) {
					// 查询箱子记录
					ManageCaseBoxExample example = new ManageCaseBoxExample();
					example.createCriteria().andCaseNoEqualTo(mac).andDoorNumEqualTo(doorNum).andIsDelEqualTo((byte) 0);
					List<ManageCaseBox> manageCaseBoxList = manageCaseBoxMapper.selectByExample(example);
					ManageCaseBox manageCaseBox = manageCaseBoxList.get(0);
					// 插入一条记录
					AccessRecord record = new AccessRecord();
					record.setBoxId(manageCaseBox.getId());
					record.setCreateDay(dateStr);
					record.setCreateTime(date);
					record.setSource(AllConst.ACCESS_RECORD_SOURCE.ADMIN_SOURCE);
					record.setType(AllConst.ACCESS_RECORD_TYPE.OPEN_DOOR_TYEP);
					record.setUserId("柜体操作");
					accessRecordMapper.insertSelective(record);
					map.put("code", 200);
					map.put("message", "开柜成功");
				} else {// 一键开门
						// 插入多条记录
						// 查询箱子记录
					List<AccessRecord> list = new ArrayList<AccessRecord>();
					ManageCaseBoxExample example = new ManageCaseBoxExample();
					example.createCriteria().andCaseNoEqualTo(mac).andIsDelEqualTo((byte) 0);
					List<ManageCaseBox> manageCaseBoxList = manageCaseBoxMapper.selectByExample(example);
					if (!manageCaseBoxList.isEmpty()) {
						manageCaseBoxList.forEach(a -> {
							AccessRecord record = new AccessRecord();
							record.setBoxId(a.getId());
							record.setCreateDay(dateStr);
							record.setCreateTime(date);
							record.setSource(AllConst.ACCESS_RECORD_SOURCE.ADMIN_SOURCE);
							record.setType(AllConst.ACCESS_RECORD_TYPE.ONE_OPEN_DOOR_TYEP);
							record.setUserId("柜体操作");
							record.setCharge(BigDecimal.valueOf(0));
							record.setUseTime(0l);
							list.add(record);
						});
						accessRecordMapper.insertBatch(list);
						map.put("code", 200);
						map.put("message", "一键开启成功");

					} else {
						map.put("code", 400);
						map.put("message", "系统错误");

					}
				}
			}else{
				map.put("code", 555);
				map.put("message", "请求超时");
			}
		} else {
			map.put("code", 444);
			map.put("message", "不要瞎几把搞");
		}
		return map;
	}

	/**
	 * @author liuCheng
	 * @since 2019年1月23日 下午2:00:44
	 * @param doorNum
	 * @param mac
	 * @param timestamp
	 * @param token
	 * @return 柜体的禁用按钮
	 * 
	 */
	@ResponseBody
	@RequestMapping("/updateSwitchToSwimToCase")
	public Map<String, Object> updateSwitchToSwimToCase(Integer doorNum, String mac, Long timestamp, String token,Byte type) {
		Map<String, Object> map = new HashMap<>();
		String sha1 = SecurityUtil.sha1(timestamp.toString());
		if (sha1.equals(token)) {
			long time = new Date().getTime();
			SysConstExample sysExample = new SysConstExample();
			sysExample.createCriteria().andNameEqualTo(AppConfig.REQEST_TIMEOUT);
			List<SysConst> selectByExample = sysConstMapper.selectByExample(sysExample);
			SysConst sysConst = selectByExample.get(0);
			String value = sysConst.getValue();
			Long valueOf = Long.valueOf(value);
			if (time - timestamp < valueOf) {
				ManageCaseBoxExample selectExample = new ManageCaseBoxExample();
				selectExample.createCriteria().andCaseNoEqualTo(mac).andDoorNumEqualTo(doorNum).andIsDelEqualTo((byte) 0);
				// 查询
				List<ManageCaseBox> manageCaseBoxList = manageCaseBoxMapper.selectByExample(selectExample);
				ManageCaseBox manageCaseBox = manageCaseBoxList.get(0);
				Byte useStatus = manageCaseBox.getUseStatus();
				Byte switchStatus = manageCaseBox.getSwitchStatus();
				if (Byte.valueOf("1").equals(useStatus)) {
					map.put("code", 400);
					map.put("message", "使用中，不可关闭");
				} else {
					ManageCaseBox record = new ManageCaseBox();
					if (Byte.valueOf("1").equals(switchStatus)) {
						record.setSwitchStatus((byte) 0);
					} else {
						record.setSwitchStatus((byte) 1);
					}
					ManageCaseBoxExample example = new ManageCaseBoxExample();
					example.createCriteria().andCaseNoEqualTo(mac).andDoorNumEqualTo(doorNum).andIsDelEqualTo((byte) 0);
					manageCaseBoxMapper.updateByExampleSelective(record, example);
					map.put("code", 200);
					map.put("message", "操作成功");
				}
			}else{
				map.put("code", 555);
				map.put("message", "请求超时");
			}
		} else {
			map.put("code", 444);
			map.put("message", "不要瞎几把搞");
		}
		return map;
	}

}
